<template>
  <div class="login">
    <el-form :model="loginForm" :rules="rules" ref="loginForm" label-width="100px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="loginForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="loginForm.password"  show-password></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="login">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {userLogin}  from  '../util/axios'

import{mapActions}  from 'vuex'
export default {
  data() {
    return {
      loginForm: {
        username: "",
        password: ""
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 15, message: "长度在 3 到 15 个字符", trigger: "blur" }
        ]
      }
    };
  },
  components: {}, 


  beforeRouteLeave(to,from,next){
          

          if(sessionStorage.getItem('user')==null){

            next('/login')
            location.reload()
          }else{
            next()
          }
  },
  methods: {    
          ...mapActions(['changeUserInfoAction'])    ,           //  this.$refs.loginForm.validate(valid => 规则验证器
    login() {                 //valid就是用来验证是否满足规则rules
      this.$refs.loginForm.validate(valid => {
        if (valid) {
      
          // console.log(this.loginForm);
              

            userLogin(this.loginForm) //数据库数据
            .then(res=>{
          
              if(res.data.code==200){
         
                console.log(res.data.list);    
                  this.$message.success(res.data.msg)           //对象转字符串
                // sessionStorage.setItem('userInfo',JSON.stringify(res.data.list))
                this.changeUserInfoAction(res.data.list)            //登录的信息
                 this.$router.push('/index')
                
              }else{
                 this.$message.error(res.data.msg)
              }
            })

       
           
        } else {
          this.$message.error("登录失败")
        
        
        }
      });
    }
  }
};
</script>

<style lang="" scoped>
.login {
  width: 100vw;
  height: 100vh;
  background-color: aqua;
}
.el-form {
  width: 400px;
  height: 200px;
  position: absolute;
  margin: -100px -200px;
  left: 50%;
  top: 50%;
}
</style>
